package com.zhouixi.service;
import cn.hutool.core.text.StrPool;
import com.alibaba.fastjson.JSON;
import com.zhouixi.entity.LocalMessageQueue;
import com.zhouixi.entity.Message;
import com.zhouixi.repository.NodeRegistry;
import com.zhouixi.repository.SessionManager;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.WebSocketSession;
import java.util.Objects;
import java.util.UUID;
import static com.zhouixi.constant.BaseConstant.BASE_TOPIC;
import static com.zhouixi.entity.Message.MessageStatus.SENDING;
import static com.zhouixi.entity.Message.MessageType.TEXT;

@Service
@Slf4j
public class MessageService {
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Resource
    private MessageStorageService messageStorageService;

    @Resource
    private NodeRegistry nodeRegistry;

    @Resource
    private LocalMessageQueue localMessageQueue ;

    @Resource
    private SessionManager sessionManager ;

    public void sendMessage(Long senderId, Long receiverId, String content) {
        // 构建完整消息对象
        Message message = getMessage(senderId, receiverId, content);

        // 保存消息到数据库
        messageStorageService.saveMessage(message);

        String currentNodeId = nodeRegistry.getCurrentNodeId();

        String opNode = nodeRegistry.getOpNode(receiverId);

        String msgJson = JSON.toJSONString(message);
        if (Objects.equals(currentNodeId,opNode)) {
            // 本地投递
            System.out.println("进行本地投递，接收者ID：" + receiverId);
            localMessageQueue.addMessage(receiverId,msgJson );
            return ;
        }
        // 跨节点路由（发送到RocketMQ）
        String topic = BASE_TOPIC + StrPool.DOT + receiverId;
        SendResult sendResult = rocketMQTemplate.syncSend( topic, msgJson);
        log.info("投递同步消息：{}",sendResult);
    }

    private static Message getMessage(Long senderId, Long receiverId, String content) {
        Message message = new Message();
        message.setMsgId(UUID.randomUUID().toString());
        message.setSenderId(senderId);
        message.setReceiverId(receiverId);
        message.setContent(content);
        message.setType(TEXT.getCode());
        message.setTimestamp(System.currentTimeMillis());
        message.setStatus(SENDING.getCode());
        return message;
    }
}